package com.intct.hbase.ddl.table;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;

/**
 * @author gufg
 * @since 2025-08-05 16:11
 */
public class AlterTable {
    public static void main(String[] args) throws IOException {
        // 创建HBase连接
        Connection connection = ConnectionFactory.createConnection();

        // 获取Admin实例
        Admin admin = connection.getAdmin();

        // 表名实例
        TableName tableName = TableName.valueOf("intct83", "t5_api");

        try {
            // 查找旧表信息
            TableDescriptor oldTableDescriptor = admin.getDescriptor(tableName);
            String familyName = "f1";

            // 查找原表中对应列族名称
            ColumnFamilyDescriptor oldColumnFamily = oldTableDescriptor.getColumnFamily(familyName.getBytes());

            // 判断表是否存--表存在
            if (admin.tableExists(tableName)) {

                // 表描述
                TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(oldTableDescriptor);

                // 增加列族
                // 判断原表中不存某个列族
                if (oldColumnFamily == null) {
                    ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(familyName.getBytes());
                    columnFamilyDescriptorBuilder.setMaxVersions(5);
                    tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());
                } else {
                    // 修改列族
                    ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder(familyName.getBytes());
                    columnFamilyDescriptorBuilder.setMaxVersions(5);
                    tableDescriptorBuilder.modifyColumnFamily(columnFamilyDescriptorBuilder.build());
                }

                // 删除列族
                // tableDescriptorBuilder.removeColumnFamily(familyName.getBytes());

                // 修改表
                admin.modifyTable(tableDescriptorBuilder.build());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
